package com.timmy.bluetooth;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.timmy.bluetooth.bluetoothData.DataParse;
import com.timmy.bluetooth.bluetoothData.OnBackDataListener;
import com.timmy.bluetooth.bluetoothData.ReceiveData;
import com.timmy.bluetooth.connect.BluetoothConnectClientManager;
import com.timmy.bluetooth.connect.Command;
import com.timmy.bluetooth.connect.IBluetoothReceiveDataListener;

/**
 * 显示电量
 */
public class InfoActivity extends AppCompatActivity {

    private DataParse mDataParse;
    private BluetoothConnectClientManager mBluetoothClientManager;
    private TextView mTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_info);

        mTv = (TextView) findViewById(R.id.tv_ele);
        Button btn = (Button) findViewById(R.id.info_btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(InfoActivity.this, ShakeActivity.class);
                startActivity(intent);
                InfoActivity.this.finish();
            }
        });

//        openSendChannel
        BluetoothConnectClientManager.getInstance().setCommand(Command.getInstance());
        BluetoothConnectClientManager.getInstance().openSendChannel();

        bluetoothManager();
    }

    private void bluetoothManager() {
        initData();
        mBluetoothClientManager = BluetoothConnectClientManager.getInstance();
        mBluetoothClientManager.setBluetoothReceiveDataListener(dataListener);
    }

    private void initData() {
        if (mDataParse == null) {
            mDataParse = new DataParse();
        }

        mDataParse.setOnBaseShockCompleteListener(onBackDataListener);
    }

    /**
     * 解析后的数据
     */
    OnBackDataListener onBackDataListener = new OnBackDataListener() {
        @Override
        public void onData(ReceiveData receiveData) {
            //获取设备电量
            if (receiveData.getBatteryValue() != -1) {
                final byte powerValue = receiveData.getBatteryValue();

                InfoActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mTv.setText("电量: " + powerValue);
                    }
                });

            }
        }
    };

    /**
     * 蓝牙接受到的数据
     */
    IBluetoothReceiveDataListener dataListener = new IBluetoothReceiveDataListener() {
        @Override
        public void onBLEReceiveData(byte[] data) {

            if (mDataParse != null) {
                //解析数据
                mDataParse.startParseData(data);
            }
        }

        @Override
        public void onVersion(byte[] version) {
        }
    };
}
